<template>
  <div>
    <!-- -->
    <el-dialog
      title="预约"
      :visible.sync="addappointmentDialog"
      v-if="addappointmentDialog"
      width="1000px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="beforeClose"
      :before-close="beforeClose"
    >
      <div style="max-height: 70vh; overflow-y: auto">
        <el-row>
          <el-col :span="11">
            <el-form
              :model="ruleForm"
              :rules="rules"
              ref="ruleForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <!-- <el-form-item label="病历号">
                <el-input
                  v-model="ruleForm.medicalRecordNum"
                  style="width: 300px"
                  placeholder="不填写病历号则自动生成"
                ></el-input>
              </el-form-item> -->
              <el-form-item label="患者姓名" prop="patientName">
                <el-input
                  v-model="ruleForm.patientName"
                  style="width: 300px"
                  placeholder="请输入患者姓名"
                ></el-input>
              </el-form-item>
              <el-form-item label="预约门诊" prop="outpatientService">
                <el-select
                  v-model="ruleForm.outpatientService"
                  style="width: 300px"
                  @change="initOptions3"
                >
                  <el-option
                    :label="item.label"
                    :value="item.label"
                    v-for="(item, index) in outpatientOptions"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="预约科室">
                <el-select v-model="ruleForm.department" style="width: 300px">
                  <el-option
                    :label="item.label"
                    :value="item.label"
                    v-for="(item, index) in administrativeOptions"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="电话"
                prop="linkPhone"
                :rules="[
                  {
                    required: true,
                    message: '电话不能为空',
                    trigger: 'blur'
                  },
                  {
                    min: 11,
                    max: 11,
                    message: '长度11个数字',
                    trigger: 'blur'
                  },
                  {
                    pattern: /^((0\d{2,3}-\d{7,8})|(1[356789]\d{9}))$/,
                    message: '手机号格式不正确',
                    trigger: 'blur'
                  }
                ]"
              >
                <el-input
                  v-model="ruleForm.linkPhone"
                  style="width: 210px"
                  maxlength="11"
                  placeholder="请输入患者电话"
                ></el-input>
                <el-select
                  v-model="ruleForm.personalRelationship"
                  style="width: 80px; margin-left: 10px"
                >
                  <el-option
                    :label="item.dictLabel"
                    :value="item.dictLabel"
                    v-for="(
                      item, index
                    ) in sysUserSexerm_personal_relationshipOptions"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="出生日期">
                <el-date-picker
                  v-model="ruleForm.birthday"
                  type="date"
                  placeholder="选择出生日期"
                  value-format="yyyy-MM-dd"
                  style="width: 300px"
                  :picker-options="pickerOptions1"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="ruleForm.sex">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="预约类型">
                <el-radio-group v-model="ruleForm.appointmentType">
                  <el-radio :label="1">普通预约</el-radio>
                  <el-radio :label="2">待确定预约</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="患者来源">
                <el-select
                  style="width: 300px"
                  v-model="ruleForm.patientSource"
                >
                  <el-option
                    :label="item.dictLabel"
                    :value="+item.dictValue"
                    v-for="(item, index) in sysUserSexerm_patient_sourceOptions"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="预约医生" prop="attendingDoctor">
                <el-select
                  style="width: 300px"
                  v-model="ruleForm.attendingDoctor"
                >
                  <el-option
                    :label="item.nickName"
                    :value="item.nickName"
                    v-for="(item, index) in userOptions"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="身份证号"
                prop="identificationCard"
                :rules="[
                  {
                    required: true,
                    message: '身份证号不能为空',
                    trigger: 'blur'
                  },
                  {
                    pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                    message: '身份证号格式不正确',
                    trigger: 'blur'
                  }
                ]"
              >
                <el-input
                  v-model="ruleForm.identificationCard"
                  style="width: 300px"
                  placeholder="请输入身份证号"
                />
              </el-form-item>
              <el-form-item label="预约人" prop="registerUserId">
                <el-select
                  style="width: 300px"
                  v-model="ruleForm.registerUserId"
                >
                  <el-option
                    :label="item.nickName"
                    :value="item.userId"
                    v-for="(item, index) in userOptions"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input
                  type="textarea"
                  v-model="ruleForm.remark"
                  style="width: 300px"
                ></el-input>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="6">
            <p style="padding: 0; margin: 0; font-size: 18px">预约时段</p>
            <HR></HR>
            <el-form
              :model="ruleForm1"
              ref="ruleForm1"
              class="demo-ruleForm"
            >
              <el-form-item
                prop="dateTime"
                :rules="[
                  {
                    required: true,
                    message: '预约日期不能为空',
                    trigger: 'change'
                  }
                ]"
              >
                <el-date-picker
                  v-model="ruleForm1.dateTime"
                  type="date"
                  @change="changeDate"
                  :picker-options="pickerOptions"
                  style="margin-bottom: 10px; width: 100%"
                  placeholder="选择日期"
                  format="yyyy 年 MM 月 dd 日"
                  :clearable="false"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
            </el-form>

            <FullCalendar
              class="demo-app-calendar"
              :options="calendarOptions"
              ref="fullCalendar"
            >
              <template v-slot:eventContent="arg">
                <b>{{ arg.timeText }}</b>
                <i>{{ arg.event.title }}</i>
              </template>
            </FullCalendar>
          </el-col>
          <el-col :span="7" style="padding-left: 20px">
            <p style="padding: 0; margin: 0; font-size: 18px">预约项目</p>
            <HR></HR>
            <el-checkbox-group
              v-model="projectList"
              style="display: flex; flex-wrap: wrap"
            >
              <el-checkbox
                v-for="item in projectListOptios"
                :label="item.appointmentName"
                :key="item.id"
                style="flex: 1; margin-top: 5px"
                >{{ item.appointmentName }}</el-checkbox
              >
            </el-checkbox-group>
          </el-col>
        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary" @click="submit">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  sysUserSexerm_patient_source,
  allList,
  sysUserSexerm_personal_relationship,
  deptTree,
  deptTreeByName,
  projectList,
  appointmentAdd,
  dropdownList
} from '@/api/allApi.js'

import moment from 'moment'
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import { INITIAL_EVENTS, createEventId } from '@/utils/event-utils.js'

export default {
  name: 'EitcErmPcAddappointmentDialog',
  components: {
    FullCalendar
  },
  props: {
    addappointmentDialog: {
      type: Boolean,
      default: false
    },
    timeArr: {
      type: Array,
      default: []
    },
    timeObj: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      ruleForm: {
        sex: 1,
        appointmentType: 1
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 86400000;
        },
      },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      rules: {
        patientName: [
          { required: true, message: '请输入患者姓名', trigger: 'blur' }
        ],
        linkPhone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        attendingDoctor: [
          { required: true, message: '请选择预约医生', trigger: 'change' }
        ],
        outpatientService: [
          { required: true, message: '请选择预约门诊', trigger: 'change' }
        ],
        registerUserId: [
          { required: true, message: '请选择预约人', trigger: 'change' }
        ],
        identificationCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' }
        ]
      },
      projectListOptios: [],
      projectList: [],
      userOptions: [],
      outpatientOptions: [],
      administrativeOptions: [],
      sysUserSexerm_personal_relationshipOptions: [], // 与本人关系
      sysUserSexerm_patient_sourceOptions: [], // 患者来源

      calendarOptions: {
        plugins: [
          dayGridPlugin,
          timeGridPlugin,
          interactionPlugin // needed for dateClick
        ],
        events: [],
        initialDate: moment().format('YYYY-MM-DD'), // 自定义设置背景颜色时一定要初始化日期时间
        locale: 'zh-cn',
        // headerToolbar: {
        //   left: 'prev,next today',
        //   center: 'title',
        //   right: 'dayGridMonth,timeGridWeek,timeGridDay'
        // },
        buttonText: {
          today: '今天'
        },
        slotMinTime: '08:00', //开始时间
        allDaySlot: false,
        headerToolbar: false,
        initialView: 'timeGridDay',
        initialEvents: INITIAL_EVENTS, // alternatively, use the `events` setting to fetch from a feed
        editable: true,
        selectable: true,
        selectMirror: true,
        dayMaxEvents: true,
        weekends: true,
        select: this.handleDateSelect,
        eventClick: this.handleEventClick,
        eventsSet: this.handleEvents,
        editable: true,
        eventDrop: this.handleEventDrop
        /* you can update a remote database when these fire:
        eventAdd:
        eventChange:
        eventRemove:
        */
      },

      currentEvents: [],
      calendarApi: '',
      calendarTitle: '',
      defaultDate: '',
      ruleForm1: {
        dateTime: ''
      },
      timeList: []
    }
  },

  mounted() {
    this.initOptions()
    this.initOptions2()
    this.initProjectList()
    this.initDropdownList()

    this.$nextTick(() => {
      this.calendarApi = this.$refs.fullCalendar.getApi()
      this.calendarTitle = this.calendarApi.view.title // 获取日历标题
      this.defaultDate = moment(new Date()).format('YYYY-MM-DD') // 获取当前日期
      // this.calendarApi.gotoDate(this.defaultDate) // 跳转到当前日期
      this.calendarApi.changeView('timeGridDay') // 切换视图为日视图

      if (this.timeArr.length) {
        this.fetchEvents()
      }
      if (Object.keys(this.timeObj).length) {
        console.log(this.timeObj, 'this.timeObj')
        this.ruleForm = { ...this.timeObj }
        this.projectList = this.timeObj.appointmentProject.split(",")
        this.ruleForm1.dateTime =
          this.timeObj.appointmentStartTime.split(' ')[0]
        this.calendarApi.gotoDate(this.ruleForm1.dateTime) // 跳转到当前日期
        this.calendarOptions.events = [
          {
            id: 1,
            start: this.formatTime(this.timeObj.appointmentStartTime),
            end: this.formatTime(this.timeObj.appointmentEndTime)
          }
        ]
        this.timeList = [
          {
            id: 1,
            appointmentStartTime: this.formatTime(
              this.timeObj.appointmentStartTime
            ),
            appointmentEndTime: this.formatTime(this.timeObj.appointmentEndTime)
          }
        ]
        this.initOptions3(1)
      }
    })
  },

  methods: {
    async initDropdownList() {
      const res1 = await dropdownList('erm_patient_source') // 患者来源
      const res2 = await dropdownList('erm_personal_relationship') // 与患者关系

      this.sysUserSexerm_patient_sourceOptions = res1.data
      this.sysUserSexerm_personal_relationshipOptions = res2.data

    },
    fetchEvents() {
      if (this.timeArr) {
        this.calendarOptions.events = []
        console.log(this.timeArr[0], 'this.timeArr[0]')
        this.ruleForm1.dateTime = this.timeArr[0].start.split(' ')[0]
        this.calendarOptions.events = this.timeArr
        this.calendarApi.gotoDate(this.ruleForm1.dateTime) // 跳转到当前日期
        this.timeList = [
          {
            id: this.timeArr[0].id,
            appointmentStartTime: this.timeArr[0].start,
            appointmentEndTime: this.timeArr[0].end
          }
        ]
        console.log(this.calendarOptions.events, 9999)
      }
    },
    async initProjectList() {
      const res = await projectList()
      this.projectListOptios = res.data
    },
    async initOptions() {
      const res1 = await allList()
      this.userOptions = res1.rows
    },
    async initOptions2() {
      const res = await deptTree()
      this.outpatientOptions = res.data
    },
    async initOptions3(val) {
      if (val) {
        const res = await deptTreeByName(this.ruleForm.outpatientService)
        this.administrativeOptions = res.data
      } else {
        const res = await deptTreeByName(this.ruleForm.outpatientService)
        this.administrativeOptions = res.data
        this.ruleForm.department = ''
      }
    },
    handleWeekendsToggle() {
      this.calendarOptions.weekends = !this.calendarOptions.weekends // update a property
    },

    handleDateSelect(selectInfo) {
      if (!this.ruleForm1.dateTime){
        let calendarApi = selectInfo.view.calendar
        calendarApi.unselect() // clear date selection
        return this.$message.error('请先选择预约日期')
      }
      if (this.timeList.length >= 1){
        let calendarApi = selectInfo.view.calendar
        calendarApi.unselect() // clear date selection
        return this.$message.error(
          '当前医生当天时间已有预约，请选择预约其他时间段'
          )
      }
        let calendarApi = selectInfo.view.calendar
      calendarApi.unselect() // clear date selection
      calendarApi.addEvent({
        id: createEventId(),
        start: this.formatTime(selectInfo.startStr),
        end: this.formatTime(selectInfo.endStr)
      })
      this.timeList.push({
        id: createEventId(),
        appointmentStartTime: this.formatTime(selectInfo.startStr),
        appointmentEndTime: this.formatTime(selectInfo.endStr)
      })
    },
    formatTime(time) {
      return moment(time).format('YYYY-MM-DD HH:mm')
    },
    formatDate(time) {
      return moment(time).format('YYYY-MM-DD')
    },
    changeDate() {
      this.calendarApi.gotoDate(this.ruleForm1.dateTime)
    },
    handleEventDrop(selectInfo) {
      console.log(selectInfo, 6666)
    },

    handleEventClick(clickInfo) {
      this.$confirm('是否删除该时间段?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.timeList = []
        clickInfo.event.remove()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },

    handleEvents(events) {
      this.currentEvents = events
    },
    beforeClose() {
      this.$emit('closeDialog')
    },
    beforeClose() {
      this.$confirm('确认退出吗？退出将不会保留当前填写数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.calendarOptions.events = []
          this.$emit('closeDialog')
        })
        .catch((err) => {
          err
        })
    },
    submit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
        this.$refs.ruleForm1.validate(async (valid) => {
            if (valid) {
              if (this.timeList.length === 0)
                return this.$message.error('请选择预约时段!')
              console.log(this.projectList, 'this.projectList')
              if (this.projectList.length === 0)
                return this.$message.error('请选择预约项目!')
              let obj = this.ruleForm
              obj.appointmentStartTime = this.timeList[0].appointmentStartTime
              obj.appointmentEndTime = this.timeList[0].appointmentEndTime
              obj.appointmentProject = this.projectList.join()

              const res = await appointmentAdd(obj)
              if (res.code !== 200) return this.$message.error(res.msg)
              this.$message.success('预约成功')
              this.$emit('closeDialog')
            } 
          })
        } 
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__wrapper {
  top: -20px !important;
}
::v-deep .demo-app-calendar {
  height: 750px;
}
</style>